package com.itlaobing.exam.dao;

import chai.ningning.foundation.jdbc.DataAccessException;
import chai.ningning.foundation.jdbc.DatabaseType;
import chai.ningning.foundation.jdbc.JdbcHelper;
import chai.ningning.foundation.jdbc.RowMapper;
import com.itlaobing.exam.entity.User;
import com.itlaobing.exam.support.UserRole;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Objects;
import java.util.logging.Logger;

public class UserDao {

    private final Logger logger = Logger.getLogger( this.getClass().getName() );

    private RowMapper<Integer> idMapper = new RowMapper<Integer>() {
        @Override
        public Integer wrap(ResultSet rs) throws DataAccessException {
            Integer id = null ;
            try {
                id = rs.getInt( 1 ) ;
            } catch (SQLException cause ) {
                throw new DataAccessException( "无法获取下一个主键" , cause );
            }
            return id ;
        }
    };

    private RowMapper<User> userMapper = new RowMapper<User>() {
        @Override
        public User wrap(ResultSet rs) throws DataAccessException {
            try {
                User u = new User() ;

                int id = rs.getInt("id");
                u.setId(id);

                String username = rs.getString("username");
                u.setUsername(username);

                String password = rs.getString("password");
                u.setPassword(password);

                String salt = rs.getString("salt");
                u.setSalt(salt);

                String nickname = rs.getString("nickname");
                u.setNickname(nickname);

                String name = rs.getString("name");
                u.setName( name );

                String gender = rs.getString("gender");
                u.setGender( gender );

                java.sql.Date date1 = rs.getDate( "birthdate" );
                if( Objects.nonNull( date1 ) ) {
                    LocalDate birthdate = date1.toLocalDate();
                    u.setBirthdate( birthdate );
                }

                java.sql.Date date2 = rs.getDate( "join_date" );
                if( Objects.nonNull( date2 ) ) {
                    LocalDate joinDate = date2.toLocalDate();
                    u.setJoin_date( joinDate );
                }

                // 没有处理角色 user_role

                return u ;
            } catch ( SQLException cause ) {
                throw new RuntimeException( "封装User实例时发生错误" , cause );
            }
        }
    };

    public boolean save( User user ) {
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        String sql = "INSERT INTO t_users ( username , password , salt , join_date , user_role , id ) VALUES ( ? , ? , ? , ? , ? , ? )" ;
        LocalDate birthdate = user.getJoin_date() ;
        java.sql.Date date = java.sql.Date.valueOf( birthdate );
        UserRole userRole = user.getUser_role() ;
        Object[] params = { user.getUsername() , user.getPassword() , user.getSalt() , date , userRole.ordinal() , user.getId() };
        int count = h.update( sql , params );
        h.release();
        return count > 0 ;
    }

    public Integer nextId(){
        String sql = "SELECT ifnull( max(id) , 0 ) + 1 AS next_id FROM t_users " ; // MySQL
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        Integer id = h.single( sql , idMapper );
        h.release();
        return id ;
    }

    public User find( String username ) {
        logger.info( "根据用户名[ " + username + " ]查找数据库" );
        String sql = "SELECT id , username , password , salt , nickname , name , gender , birthdate , join_date , user_role FROM t_users WHERE username = ?" ; // MySQL
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        User user = h.single( sql , userMapper , username );
        h.release();
        return user ;
    }

    public boolean edit( User user ) {
        logger.info( "更新用户信息" );
        String sql = "UPDATE t_users SET nickname = ? , name = ? , gender = ? , birthdate = ? WHERE id = ? " ;
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        LocalDate birthdate = user.getBirthdate();
        java.sql.Date date = null ;
        if( Objects.nonNull( birthdate ) ) {
            date = java.sql.Date.valueOf(birthdate);
        }
        Object[] params = { user.getNickname() , user.getName() , user.getGender() , date , user.getId() } ;
        int count = h.update( sql , params );
        h.release();
        return count > 0 ;
    }

    public boolean change(User user){
        logger.info( "更新用户密码" );
        String sql = "UPDATE t_users SET password = ? WHERE id = ? " ;
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        Object[] param = { user.getPassword() , user.getId()  } ;
        int count = h.update( sql , param );
        h.release();
        return count > 0 ;
    }

    public boolean delete( User user ) {
        logger.info( "删除用户" );
        String sql = "DELETE FROM t_users WHERE id = ? " ;
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        int count = h.update( sql , user.getId() );
        h.release();
        return count > 0 ;
    }

}
